package web.servlets;

import domain.Account;
import domain.Cart;
import domain.CartItem;
import domain.Item;
import persistence.Impl.CartDAOImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SetItemQuantityServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CartDAOImpl cartDAO = new CartDAOImpl();
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        Cart cart = (Cart) session.getAttribute("cart");
        for(CartItem cartItem:cart.getCartItemList()){
            cartItem.setQuantity(Integer.parseInt(req.getParameter(cartItem.getItem().getItemId())));
            if(account!=null){
                cartDAO.updateQuantityByUserName(account.getUsername(),cartItem.getItem().getItemId(), Integer.parseInt(req.getParameter(cartItem.getItem().getItemId())));
            }
        }

        req.getRequestDispatcher(VIEW_CART).forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
